﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;



namespace InstaGM
{

    public partial class gui : Form
    {
        //Define tool wide variables
        public TcpClient tcpc;
        public NetworkStream ns;
        public config_item conf = new config_item();
        public Regex objToMatch { get; set; }
        public string ret { get; set; }
        public Byte[] output = new Byte[1024];
        public String responseoutput = String.Empty;
        public Byte[] cmd = System.Text.Encoding.ASCII.GetBytes("\n");
        public string cmd_txt { get; set; }
        public bool cmd_issued { get; set; }
        public bool ins_sum_issued { get; set; }
        public bool raw_cmd_issued { get; set; }
        public bool pass_sent { get; set; }
        public bool char_focus_requested { get; set; }
        public bool char_focused { get; set; }
        public static string host_val = Properties.Settings.Default.host;
        public static int port_val = Properties.Settings.Default.port;
        public static string pass_val = Properties.Settings.Default.pass;
        //Define Telecaster settom
        public static string db_name = Properties.Settings.Default.db_name;
        public static string db_user = Properties.Settings.Default.db_user;
        public static string db_pass = Properties.Settings.Default.db_pass;
        public static int db_port = Properties.Settings.Default.db_port;
        //Define Character Destination Setting
        public static bool playerTO_telnet = Properties.Settings.Default.player_to_telnet;
        public static bool playerTO_clipboard = Properties.Settings.Default.player_to_clipboard;
        bool auto_connect = Properties.Settings.Default.auto_conn;
        public bool auto_tamed = Properties.Settings.Default.auto_tamed;
        bool first_time = Properties.Settings.Default.first_time;
        bool states_to_telnet = Properties.Settings.Default.to_telnet;
        bool states_to_clipboard = Properties.Settings.Default.state_to_clipboard;
        SqlDataAdapter adapter = new SqlDataAdapter();
        public static string connectionString = "server="+host_val+";database="+db_name+";user id="+db_user+";password="+db_pass+";Trusted_Connection=no;Timeout=10;"; 
        public DataSet job_list = new DataSet();
        public BackgroundWorker bgw = new BackgroundWorker();
        public string tmp_job_name { get; set; }
        public int new_job_id { get; set; }
        public int char_sid { get; set; }
        public string char_name { get; set; }
        public string acc_name { get; set; }
        public int acc_id { get; set; }
        public string tmp = Directory.GetCurrentDirectory();
        public int insert_summon_id { get; set; }
        public Assembly Asm;
        public StreamReader summon_list;
        public StreamReader item_list;
        public StreamReader state_list;
        public StreamReader monster_list;
        public int items_read;
        public int chars_read;
        public int summons_read;
        public int states_read;
        public int monsters_read;

        public gui()
        {
            InitializeComponent();
            //These are for various clicked performed throughout InstaGM
            AddControlEvent();
        }

        //Upon the program loading these things will occur
        private void gui_load(object sender, EventArgs e)
        {
            //We have to try to load the embedded resources 
            //Just incase the lists are not present in physical folder
	        try
            {
                //Define the Assembly
                Asm = Assembly.GetExecutingAssembly();
                //Define the embedded resources
                summon_list = new StreamReader(Asm.GetManifestResourceStream("InstaGM.summon_list.txt"));
                item_list = new StreamReader(Asm.GetManifestResourceStream("InstaGM.item_list.txt"));
                state_list = new StreamReader(Asm.GetManifestResourceStream("InstaGM.state_list.txt"));
                monster_list = new StreamReader(Asm.GetManifestResourceStream("InstaGM.monster_list.txt"));
            }
            catch (Exception ex)
            {
                //If any resources fail to load
                MessageBox.Show(ex.ToString());
            }
	
            //If this is the first time this program has been loaded
            if (first_time == true)
            {
                //Show first time informational dlg
                first_time first_dlg = new first_time();
                //Show it as dialog so it must be closed before the user can continue
                first_dlg.ShowDialog();          
            }

            //If user has defined Auto-Connect 
            if (auto_connect == true)
            {
                connect_btn_Click(connect_btn, EventArgs.Empty);
            }

            //Load the Character List
            load_characters();

            //Set Item/Buff Box Instructional Tooltip
            ToolTip tooltip = new ToolTip();
            tooltip.ToolTipIcon = ToolTipIcon.Info;
            tooltip.ToolTipTitle = "Information";
            tooltip.IsBalloon = true;
            tooltip.ShowAlways = true;
            tooltip.AutoPopDelay = 500000000;
            tooltip.SetToolTip(item_grid_q, "The Item Panel is designed entirely with the user in mind.\n\nOnce you have clicked the item tab the loading process has already begun!\n\nYou can now begin searching for your item! How? Simply, scroll up/down or type an item name in the Search Box\n\nSearch Box Notes: The search box will highlight the closest result in the item list as you type it, to reset your search just blank the text by pressing backspace or alt+a then backspace.\n\nOnce you have found the item you desire, set it's # and lv/+ when applicable (lv and + are only applicable when sending Items to Clip Board)\n\nNow just click the \"Insert\" Button!");
            tooltip.SetToolTip(state_grid_q, "The Buff Panel is designed entirely with the user in mind.\n\nOnce you have clicked the buff tab the loading process has already begun!\n\nYou can now begin searching for your buff! How? Simply scroll up/down or type a buff name in the Search Box\n\nSearch Box Notes: The search box will highlight the closest result in the buff list as you type it, to reset your search just blank the text by pressing backspace or alt+a then backspace.\n\nOnce you have found the buff you desire, edit it's lv and then double click it!");
            tooltip.SetToolTip(toitemboxicon, "Items are being sent to the Item Box");
            tooltip.SetToolTip(toclipboardicon, "Items are being sent to the Clip Board");
            tooltip.SetToolTip(statetotelneticon, "States are being sent to the Game-Server (telnet)");
            tooltip.SetToolTip(statetoclipboardicon, "States are being sent to the Clip Board");
            tooltip.SetToolTip(playertotelimg, "Player commands are currently being sent to the telnet");
            tooltip.SetToolTip(playertoclipimg, "Player commands are currently being sent to the clipboard");
            tooltip.SetToolTip(spawnstotelimg, "Spawns are being sent to the the Game-Server (telnet)");
            tooltip.SetToolTip(spawntoclipimg, "Spawns are being sent to the Clip Board");
            tooltip.SetToolTip(summontotelimg, "Summons are being sent to the Game-Server (itembox)");
            tooltip.SetToolTip(summonstoclipimg, "Summons are being sent to the Clip Board");
            tooltip.SetToolTip(rcmd_lb, "Raw Command is unlocked on the \"Log\" Tab");
        }

        //Connect button is pressed
        private void connect_btn_Click(object sender, EventArgs e)
        {
            //Below we will try to define a new TCP Client to use for our Telnet communications
            try
            {
                //Define Telnet Client
                tcpc = new TcpClient(host_val, port_val);
                //Define the fetched Telnet Stream
                ns = tcpc.GetStream();
                //Set the flag for Telnet Connected
                Properties.Settings.Default.telnet_connected = true;
                Properties.Settings.Default.Save();
                //Lets disable the connect button to avoid bugs
                connect_btn.Enabled = false;
                //Define a new background worker
                bgw = new BackgroundWorker();
                //Define what the background worker will do
                bgw.DoWork += exec_conn;
                //Begin background worker to execute connection asynchronously
                bgw.RunWorkerAsync();
            }
            catch (Exception)
            {
                //If unable to connect we should display a message
                MessageBox.Show("Connection Failed!\n\nNon-Remote Setup:\n- Set Host to 127.0.0.1/Localhost\n- Set Port same as S console.port (in gameserver opt)\n\nRemote Setup:\n!!IMPORTANT!! Make sure the following has been done on the remote server:\n\n- S console.port is opened in both Windows Firewall and Router (if applicable)\n- S console._password has been set");
                //Just incase set the telnet_connected to false
                Properties.Settings.Default.telnet_connected = false;
                Properties.Settings.Default.Save();
            }
        }

        //Execute the connect function if status is not idle (already connected)
        public void exec_conn(object sender, DoWorkEventArgs e)
        {

            //Connect to Telnet
            connect(Properties.Settings.Default.pass);  

        }

        //Execute the sendcommand function 
        public void exec_send(object sender, DoWorkEventArgs e)
        {
           sendcommand(command.Text);          
        }

        //Open Host/Port Settings Menu
        private void dBSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            host_settings host = new host_settings();
            host.ShowDialog();
        }

        //Open DB Settings Menu
        private void instagm_db_settings_Click(object sender, EventArgs e)
        {
            db_settings db = new db_settings();
            db.ShowDialog();
        }

        //Open Misc Settings Menu
        private void instagm_misc_settings_Click(object sender, EventArgs e)
        {
            misc_settings misc = new misc_settings();
            misc.ShowDialog();
        }

        //Add Character to Character List
        private void add_character_btn_Click(object sender, EventArgs e)
        {
            Regex chk = new Regex("^[a-zA-Z][a-zA-Z0-9]*$");

            if (string.IsNullOrEmpty(character_name.Text))
            {
                MessageBox.Show("There is no name currently typed in");
            }
            else
            {
                if (chk.IsMatch(character_name.Text))
                {
                    //Let's check the name for a bad length
                    if (character_name.Text.Length < 5)
                    {
                        MessageBox.Show("The name you entered is not long enough, please make sure all names are 5+ characters");
                    }
                    //If not too short then proceed
                    else
                    {
                        //Name is not empty, so let's add it to the list
                        char_list.Items.Add(character_name.Text);
                        //Using a stream writer
                        using (TextWriter streamWriter = new StreamWriter(File.Create(Path.Combine(this.tmp, "character_list.txt"))))
                        {
                            foreach (string item in char_list.Items)
                            {
                                //let's write each name in the character list
                                streamWriter.WriteLine(item);
                            }
                        }
                    }
                }
                //If there were non-alphanumeric symbols in the name
                else
                {
                    MessageBox.Show("Character names may not contain symbols other than \"_\" or \"-\"");
                }
            }
        }

        //Remove Character from Character List
        private void rem_character_btn_Click(object sender, EventArgs e)
        {
            //Try to remove the item
            try
            {
                //If there is no character selected
                if (char_list.SelectedIndex == -1)
                {
                    MessageBox.Show("You must select a player name first!");
                }
                else
                {
                    //Character was selected, lets remove him frm the list
                    char_list.Items.RemoveAt(char_list.SelectedIndex);
                    //using a textwriter 
                    using (TextWriter streamWriter = new StreamWriter(File.Create(Path.Combine(this.tmp, "character_list.txt"))))
                    {
                        //For each name on the list we will write to the file
                        foreach (string item in char_list.Items)
                        {
                            streamWriter.WriteLine(item);
                        }
                    }
                }
            }
            catch
            {
                MessageBox.Show("Unexpected Error during deletion!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        //Insert Gold
        private void ins_gold_btn_Click(object sender, EventArgs e)
        {
            //Chk defines that only numbers are acceptable for this field.
            Regex chk = new Regex("^[0-9]{1,25}$");

            if (char_list.SelectedIndex == -1)
            {
                MessageBox.Show("Please select a player first!");
            }
            else
            {
                if (status.Text == "Idle")
                {
                    if (gold.Text != "")
                    {
                        //Check Gold.Text for bad things
                        if (!chk.IsMatch(gold.Text))
                        {
                            MessageBox.Show("It seems you have attempted to enter potentially harmful information in the Gold Value Box. Please remove anything but numbers from the field and try again.");
                        }
                        else
                        {
                            //Make sure the gold amount is not lethal
                            if (Convert.ToInt64(gold.Text) > 9999999999)
                            {
                                MessageBox.Show("The value you have entered in the Gold field is higher than allowed, please reduce it below 9b");
                            }
                            else
                            {
                                cmd_txt = "#insert_gold(\"" + gold.Text + "\"," + "\"" + char_list.SelectedItem.ToString() + "\")";

                                //We should check the destination of player commands
                                if (playerTO_telnet == true)
                                {
                                    if (Properties.Settings.Default.telnet_connected == false)
                                    {
                                        MessageBox.Show("Cannot transmit the command, the Telnet appears to be inactive.");
                                    }
                                    else
                                    {
                                        sendcommand(cmd_txt);
                                    }
                                }
                                else if (playerTO_clipboard == true)
                                {
                                    string clip_cmd = "";
                                    clip_cmd = cmd_txt.Replace("#", "/run ");
                                    sendtoclip(clip_cmd);
                                }
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Playername Set, Telet Not Connected");
                }
            }
        }

        //Set Value
        private void set_player_val_btn_Click(object sender, EventArgs e)
        {
            if (char_list.SelectedIndex == -1)
            {
                MessageBox.Show("You must select a player name first!");
            }
            else
            {
                if (set_val_list.SelectedIndex == -1)
                {
                    MessageBox.Show("Please select a value to be set first!");
                }
                else
                {
                    if (status.Text == "Idle")
                    {
                        if (!string.IsNullOrEmpty(set_val_val.Text))
                        {
                            //If the value should follow "HP/MP" numeric rules
                            if (set_val_list.SelectedItem.ToString() == "hp" || set_val_list.SelectedItem.ToString() == "mp")
                            {
                                cmd_txt = "#set_value(\"" + set_val_list.SelectedItem.ToString() + "\"," + "\"" + set_val_val.Text + "\"," + "\"" + char_list.SelectedItem.ToString() + "\")";
                            }
                            //If the value should follow "LV" numeric rules
                            if (set_val_list.SelectedItem.ToString() == "lv")
                            {
                                //Let's give our value a handle
                                int new_value = Convert.ToInt32(set_val_val.Text)-1;
                                //Check if the level is in proper range
                                if (new_value < 2 && new_value > 300)
                                {
                                   cmd_txt = "#set_value(\"" + set_val_list.SelectedItem.ToString() + "\"," + "\"" + new_value + "\"," + "\"" + char_list.SelectedItem.ToString() + "\")";
                                }
                                else
                                {
                                   MessageBox.Show("The level you have entered is out of range!");
                                }
                            }
                            //If the value should follow "JP" numeric rules
                            if (set_val_list.SelectedItem.ToString() == "jp")
                            {
                                //Lets give our value a handle
                                Int64 new_value = Convert.ToInt64(set_val_val.Text);
                                //Check if the amount of jp is acceptable
                                if (new_value < 10000000000)
                                {
                                    cmd_txt = "#set_value(\"" + set_val_list.SelectedItem.ToString() + "\"," + "\"" + new_value + "\"," + "\"" + char_list.SelectedItem.ToString() + "\")";
                                }
                            }
                            //If the value should follow "TP" numeric rules
                            if (set_val_list.SelectedItem.ToString() == "tp")
                            {
                                //Lets give our value a handle
                                int new_value = Convert.ToInt32(set_val_val.Text);
                                //Check if the amount of jp is acceptable
                                if (new_value > 0 && new_value < 6)
                                {
                                    cmd_txt = "#set_value(\"" + set_val_list.SelectedItem.ToString() + "\"," + "\"" + new_value + "\"," + "\"" + char_list.SelectedItem.ToString() + "\")";
                                }
                                else
                                {
                                    MessageBox.Show("The amount of tp you have entered is not acceptable stick to anything under 10 Billion");
                                }
                            }
                            //If the value should follow "PERMISSION" numeric rules
                            if (set_val_list.SelectedItem.ToString() == "perm")
                            {
                                //Lets give our value a handle
                                int new_value = Convert.ToInt32(set_val_val.Text);
                                //Check the permission value is acceptable
                                if (new_value == 100)
                                {
                                    cmd_txt = "#set_value(\"" + set_val_list.SelectedItem.ToString()+ "ission" + "\"," + "\"" + new_value + "\"," + "\"" + char_list.SelectedItem.ToString() + "\")";
                                }
                                else
                                {
                                    MessageBox.Show("The Permission you have entered is not 100 and may not work!");
                                }
                            }

                            //We should check the destination of player commands
                            if (playerTO_telnet == true)
                            {
                                if (Properties.Settings.Default.telnet_connected == false)
                                {
                                    MessageBox.Show("Cannot transmit the command, the Telnet appears to be inactive.");
                                }
                                else
                                {
                                    sendcommand(cmd_txt);
                                }
                            }
                            else if (playerTO_clipboard == true)
                            {
                                string clip_cmd = "";
                                clip_cmd = cmd_txt.Replace("#", "/run ");
                                sendtoclip(clip_cmd);
                            }
                        }
                    }
                }
            }      
        }

        //Change Job
        private void set_player_job_btn_Click(object sender, EventArgs e)
        {
            if (job_name.SelectedIndex == -1)
            {
                MessageBox.Show("Please select a value to be set first!");
            }
            else
            {
                if (status.Text == "Idle")
                {
                    string j = "job";
                    if (char_list.SelectedIndex == -1)
                    {
                        MessageBox.Show("You must Select a Player Name First!");
                    }
                    else
                    {
                        new_job_id = get_job_id(job_name.SelectedItem.ToString());
                        cmd_txt = "#set_value(\"" + j + "\"," + "\"" + new_job_id.ToString() + "\"," + "\"" + char_list.SelectedItem.ToString() + "\")";

                        //We should check the destination of player commands
                        if (playerTO_telnet == true)
                        {
                            if (Properties.Settings.Default.telnet_connected == false)
                            {
                                MessageBox.Show("Cannot transmit the command, the Telnet appears to be inactive.");
                            }
                            else
                            {
                                sendcommand(cmd_txt);
                            }
                        }
                        else if (playerTO_clipboard == true)
                        {
                            string clip_cmd = "";
                            clip_cmd = cmd_txt.Replace("#", "/run ");
                            sendtoclip(clip_cmd);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Telnet is not connected!");
                }
            }
        }

        //Learn All Skill
        private void learn_player_all_skill_btn_Click(object sender, EventArgs e)
        {
            if (char_list.SelectedIndex == -1)
            {
                MessageBox.Show("You must select a player name first!");
            }
            else
            {
                cmd_txt = "#learn_all_skill(\"" + char_list.SelectedItem.ToString() + "\")";

                //We should check the destination of player commands
                if (playerTO_telnet == true)
                {
                    if (Properties.Settings.Default.telnet_connected == false)
                    {
                        MessageBox.Show("Cannot transmit the command, the Telnet appears to be inactive.");
                    }
                    else
                    {
                        sendcommand(cmd_txt);
                    }
                }
                else if (playerTO_clipboard == true)
                {
                    string clip_cmd = "";
                    clip_cmd = cmd_txt.Replace("#", "/run ");
                    sendtoclip(clip_cmd);
                }
            }
        }

        //Kick Player
        private void kick_player_btn_Click(object sender, EventArgs e)
        {
            if (char_list.SelectedIndex == -1)
            {
                MessageBox.Show("You must select a player name first!");
            }
            else
            {
                cmd_txt = "#kick(\"" + char_list.SelectedItem.ToString() + "\")";

                //We should check the destination of player commands
                if (playerTO_telnet == true)
                {
                    if (Properties.Settings.Default.telnet_connected == false)
                    {
                        MessageBox.Show("Cannot transmit the command, the Telnet appears to be inactive.");
                    }
                    else
                    {
                        sendcommand(cmd_txt);
                    }
                }
                else if (playerTO_clipboard == true)
                {
                    string clip_cmd = "";
                    clip_cmd = cmd_txt.Replace("#", "/run ");
                    sendtoclip(clip_cmd);
                }
            }
        }

        //Learn Creature All Skill
        private void learn_creature_all_skill_btn_Click(object sender, EventArgs e)
        {
            if (char_list.SelectedIndex == -1)
            {
                MessageBox.Show("You must select a player name first!");
            }
            else
            {
                cmd_txt = "#learn_creature_all_skill(\"" + char_list.SelectedItem.ToString() + "\")";

                //We should check the destination of player commands
                if (playerTO_telnet == true)
                {
                    if (Properties.Settings.Default.telnet_connected == false)
                    {
                        MessageBox.Show("Cannot transmit the command, the Telnet appears to be inactive.");
                    }
                    else
                    {
                        sendcommand(cmd_txt);
                    }
                }
                else if (playerTO_clipboard == true)
                {
                    string clip_cmd = "";
                    clip_cmd = cmd_txt.Replace("#", "/run ");
                    sendtoclip(clip_cmd);
                }
            }
        }

        //Mute Player
        private void mute_player_btn_Click(object sender, EventArgs e)
        {
            if (status.Text == "Idle")
            {
                if (char_list.SelectedIndex == -1)
                {
                    MessageBox.Show("You must select a player name first!");
                }
                else
                {
                    if (mute_time_val.Text != "")
                    {
                        double fin_time_val = 0;

                        if (mute_time_type.Text != "")
                        {
                            if (mute_time_type.Text == "min")
                            {
                                fin_time_val = TimeSpan.FromMinutes(Convert.ToInt32(mute_time_val.Text)).TotalSeconds;
                            }
                            if (mute_time_type.Text == "hour")
                            {
                                fin_time_val = TimeSpan.FromHours(Convert.ToInt32(mute_time_val.Text)).TotalSeconds;
                            }
                            if (mute_time_type.Text == "day")
                            {
                                fin_time_val = TimeSpan.FromDays(Convert.ToInt32(mute_time_val.Text)).TotalSeconds;
                            }
                            cmd_txt = "#block_chat "+char_list.SelectedItem.ToString()+" "+fin_time_val+"";

                            //We should check the destination of player commands
                            if (playerTO_telnet == true)
                            {
                                if (Properties.Settings.Default.telnet_connected == false)
                                {
                                    MessageBox.Show("Cannot transmit the command, the Telnet appears to be inactive.");
                                }
                                else
                                {
                                    sendcommand(cmd_txt);
                                }
                            }
                            else if (playerTO_clipboard == true)
                            {
                                string clip_cmd = "";
                                clip_cmd = cmd_txt.Replace("#", "/run ");
                                sendtoclip(clip_cmd);
                            }
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Telnet not connected!");
            }
        }

        //Summon Grid Clicked
        private void dataGridView1_Click(object sender, EventArgs e)
        {
            if (status.Text == "Idle")
            {
                if (char_list.SelectedIndex == -1)
                {
                    MessageBox.Show("You must select a player name first!");
                }
                else 
                {
                    DataGridViewRow row = summon_grid.CurrentCell.OwningRow;
                    int returned_val = Convert.ToInt32(row.Cells["summon_id"].Value);
                    insert_summon_id = returned_val;

                    if (tamed.Checked == true)
                    {
                        if (Properties.Settings.Default.item_to_itembox == true)
                        {
                            if (MessageBox.Show("You can not send tamed pets to the Item Box!\n\nWould you like to send to Clip Board instead?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                            {
                                string clip_cmd = "/run insert_item(\"" + insert_summon_id + "\", 1,0,0,-2147483648, \"" + char_list.SelectedItem + "\")";
                                this.Invoke(new MethodInvoker(delegate { status.Text = "Working"; }));
                                sendtoclip(clip_cmd);
                            }
                        }
                        if (Properties.Settings.Default.item_to_clipboard == true)
                        {
                            string clip_cmd = "/run insert_item(\"" + insert_summon_id + "\", 1,0,0,-2147483648, \"" + char_list.SelectedItem + "\")";
                            this.Invoke(new MethodInvoker(delegate { status.Text = "Working"; }));
                            sendtoclip(clip_cmd);
                        }
                    }
                    else //Tamed NOT Checked
                    {
                        if (Properties.Settings.Default.item_to_itembox == true)
                        {
                            insert_summon();
                        }
                        if (Properties.Settings.Default.item_to_clipboard == true)
                        {
                            string clip_cmd = "/run insert_item(\"" + insert_summon_id + "\", 1,0,0,2, \"" + char_list.SelectedItem + "\")";
                            sendtoclip(clip_cmd);
                        }
                    }
                }
            }
        }

        //Item Grid Clicked
        private void insert_item_Click(object sender, EventArgs e)
        {
            if (char_list.SelectedIndex == -1)
            {
                MessageBox.Show("You must selected a player name first!");
            }
            else
            {
                //We should open the insert_item window now
                DataGridViewRow row = item_grid.CurrentCell.OwningRow;
                int item_id_ret = Convert.ToInt32(row.Cells["item_id"].Value);
                conf.remITEMid = item_id_ret;
                conf.ShowDialog();
                execute_insert_item();
            }
        }

        //Execute Insert Item
        public void execute_insert_item()
        {
            insert_item(conf.remITEMid, conf.remITEMamt, conf.remITEMenc, conf.remITEMlv, conf.remITEMflag);
        }

        //State Grid is Double Clicked
        private void state_grid_insert(object sender, EventArgs e)
        {
            if (char_list.SelectedIndex == -1)
            {
                MessageBox.Show("You must selected a player name first!");
            }
            else
            {
                //INSERT_STATE
                insert_state();
            }
        }

        //The Monster Spawn Button has been pressed
        private void mob_spawn_btn_Click(object sender, EventArgs e)
        {
            //If spawn type is Telnet
            if (Properties.Settings.Default.spawns_to_telnet == true)
            {
                DataGridViewRow row = mob_grid.CurrentCell.OwningRow;
                int returned_val = Convert.ToInt32(row.Cells["mob_id"].Value);
                cmd_txt = "#add_npc(gv('x', '" + char_list.SelectedItem.ToString() + "'), gv('y', '" + char_list.SelectedItem.ToString() + "')," + returned_val + ",1)";
                sendcommand(cmd_txt);
            }
            //If spawn type is Clip-Board
            if (Properties.Settings.Default.spawns_to_clipboard == true)
            {
                DataGridViewRow row = mob_grid.CurrentCell.OwningRow;
                int returned_val = Convert.ToInt32(row.Cells["mob_id"].Value);
                cmd_txt = "//regenerate " + returned_val;
                sendtoclip(cmd_txt);
            }
        }
    }
}
